package com.hk.commons.poi.excel.read;

import com.hk.commons.poi.excel.metadata.ErrorLog;
import com.hk.commons.poi.excel.metadata.ReadWorkbook;
import com.hk.commons.poi.excel.metadata.Title;
import com.hk.commons.poi.excel.read.listeners.ReadListener;
import com.hk.commons.util.CollectionUtils;
import com.hk.commons.util.ObjectUtils;
import com.hk.commons.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @param <T>
 */
public abstract class AbstractExcelReadExecutor<T> implements ExcelReadExecutor<T> {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    protected final ReadWorkbook readWorkbook;

    protected List<ReadListener<T>> listeners = new ArrayList<>();

    protected AbstractExcelReadExecutor(ReadWorkbook readWorkbook) {
        this.readWorkbook = readWorkbook;
    }

    @Override
    public final void addReadListeners(List<ReadListener<T>> readListenerList) {
        listeners.addAll(readListenerList);
    }

    protected void onStart() {
        listeners.forEach(ReadListener::onStart);
    }

    protected void onSheetStart(int sheetIndex, String sheetName, int totalRow) {
        listeners.forEach(item -> item.onSheetStart(sheetIndex, sheetName, totalRow));
    }

    protected void onRowStart(int sheetIndex, String sheetName, int row) {
        listeners.forEach(item -> item.onRowStart(sheetIndex, sheetName, row));
    }

    protected void onRowEnd(int sheetIndex, String sheetName, int row, T data, List<Title> titleList) {
        listeners.forEach(item -> item.onRowEnd(sheetIndex, sheetName, row, data, titleList));
    }

    public void onSheetEnd(int sheetIndex, String sheetName) {
        listeners.forEach(item -> item.onSheetEnd(sheetIndex, sheetName));
    }

    protected List<ErrorLog<T>> onCompleted() {
        var result = new ArrayList<ErrorLog<T>>();
        listeners.forEach(item -> {
            var errorLogs = item.onCompleted();
            if (CollectionUtils.isNotEmpty(errorLogs)) {
                result.addAll(errorLogs);
            }
        });
        return result;
    }

    protected final Object trimToValue(Object value) {
        var result = ObjectUtils.toString(value);
        if (readWorkbook.isAutoTrim()) {
            result = StringUtils.trimToNull(result);
        }
        if (StringUtils.isNotEmpty(result) && readWorkbook.isIgnoreLineBreak()) {
            result = StringUtils.replace(result, StringUtils.LF, StringUtils.EMPTY);
        }
        return result;
    }

}
